package com.my.lab;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Parcel;
import android.telephony.TelephonyManager;
import android.text.format.Time;
import android.util.Log;

import com.android.internal.telephony.ITelephony;

public class PhoneUtils {

    static public ITelephony getItelephony(TelephonyManager tm) {
        Method m = null;
        try {
            m = tm.getClass().getDeclaredMethod("getITelephony", null);
            m.setAccessible(true);
            return (ITelephony) m.invoke(tm, null);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ;
        return null;
    }

    static public void printAllInform(Class cls) {

        Method[] ms = cls.getDeclaredMethods();
        int i = 0;
        for (; i < ms.length; i++) {
            Log.e("method name", "" + ms[i].getName());
        }
        Field[] allFileds = cls.getFields();
        int j = 0;
        for (; j < ms.length; j++)
            Log.e("method field", "" + allFileds[j].getName());
    }

    static boolean mKeepListenFlag = true;

    public static void ListenLog() {
        Thread t = new Thread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                Log.v("Fuck", "Start listening log");
                String[] cmds = { "logcat", "-d" , " -v process" };
                String[] cmdClear = { "logcat", "-c" };
                String[] cmdformat = {"logcat",""} ;
                Process process = null;
                InputStream is = null;
                DataInputStream dis = null;
                String line = "";
                BufferedReader br = null ;
                Runtime runtime = Runtime.getRuntime();
                try {
                    process = runtime.exec("/system/bin/logcat ");
                    is = process.getInputStream();
                    br = new BufferedReader( new InputStreamReader(is) ,1024);
                    while(true) {
                        
                        if(br.ready()) {
                            while((line = br.readLine())!= null) {
//                                Log.d("log", line);
                                if (line.contains("ActivityManager")) {
                                    Log.e("log", line);
                                    runtime.exec(cmdClear);
                                }
                            }
                        } else {
                            continue ;
                        }
                        
                    }  

/*                    while(true) {
                        process = runtime.exec(cmds);
                        is = process.getInputStream();
                        br = new BufferedReader(new InputStreamReader(is));
                        if(br.ready()) {
                            while ((line = br.readLine()) != null) {
                                Log.d(this.getClass().getName(), line);
                                if (line.contains("ActivityManager")) {
                                }
                            }                        
                        }else {
                            runtime.exec(cmdClear);
                            Thread.sleep(500);
                        }
                    }*/


                } catch (IOException ie) {
                    Log.v("Fuck", "finished listen");
                    ie.printStackTrace();
                } finally {
                    Log.v("Fuck", "finished listen2");
                    try {
                        if (dis != null) {
                            dis.close();
                        }
                        if (is != null) {
                            is.close();
                        }
                        if (process != null) {
                            process.destroy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        });
        // mKeepListenFlag�Ǹ���Ա��������Ϊ���ó������ʱ��ֹ�̵߳ģ�������ܲ��������������Ȼ������߳̾������˶����Android�߳̿ɲ�����ΪActivity���˳�����ֹ��
        mKeepListenFlag = true;
        t.start();
    }

    /**
     * ��������Ψһ���⹫�����½��߳�ִ�У������������󣬵��³������
     */
    public static void Log() {
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                getLog();
            }
        });
        th.start();

    }

    /**
     * ������־
     */
    private static void getLog() {
        System.out.println("--------func start--------");
        try {
            ArrayList<String> cmdLine = new ArrayList<String>();
            cmdLine.add("logcat");
            cmdLine.add("-d");

            ArrayList<String> clearLog = new ArrayList<String>();
            clearLog.add("logcat");
            clearLog.add("-c");

            Process process = Runtime.getRuntime().exec(cmdLine.toArray(new String[cmdLine.size()]));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                Runtime.getRuntime().exec(clearLog.toArray(new String[clearLog.size()]));
                Log.d("runtime",str);
//                sendLogUDP(logToJobj(str));

            }
            if (str == null) {
                System.out.println("--   is null   --");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("--------func end--------");
    }

    /**
     * ��Logת����JSONObject
     * 
     * @param s
     * @return
     */
    private static JSONObject logToJobj(String s) {

        String s1 = s.substring(0, 1);

        String s2 = s.substring(s.indexOf('/') + 1, s.indexOf('('));

        String s3 = s.substring(s.indexOf('(') + 1, s.indexOf(')'));

        String s4 = s.substring(s.indexOf(':') + 1);

        JSONObject obj = new JSONObject();
        try {
            // obj.put("PhoneID", phoneID);
            obj.put("Type", s1.trim());
            obj.put("Tag", s2.trim());
            obj.put("ThreadID", s3.trim());
            obj.put("Msg", s4.trim());
            obj.put("Time", getTime());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * ͨ��UDP��ʽ������ݵ�������
     * 
     * @param obj
     */
    private static void sendLogUDP(JSONObject obj) {
        String objStr = obj.toString();
        int port = 8081;
        DatagramSocket ds = null;
        InetAddress ia = null;
        if (obj != null) {
            try {
                ds = new DatagramSocket();
                ia = InetAddress.getByAddress(null);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            int msgLenght = objStr.length();
            byte[] msgByte = objStr.getBytes();

            DatagramPacket dp = new DatagramPacket(msgByte, msgLenght, ia, port);

            try {
                ds.send(dp);
            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            }
        }
    }

    /**
     * ��ȡ��ǰʱ��
     * 
     * @return
     */
    private static String getTime() {
        Time time = new Time("GMT+8");
        time.setToNow();
        int year = time.year;
        int month = time.month;
        int day = time.monthDay;
        int minute = time.minute;
        int hour = time.hour;
        int sec = time.second;
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + sec;
    }

}
